package com.yunsoft.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.yunsoft.dao.UserDao;
import com.yunsoft.pojo.User;

@Repository
public class UserDaoImpl implements UserDao {

	
	@Autowired
	protected SessionFactory sessionFactory;
	

	// 获取和当前线程绑定的Seesion
	private Session currentSession() {
		return sessionFactory.getCurrentSession();
	}
	
	public User addUser(User u) {
		Session session = currentSession();
		Serializable id = session.save(u);
		return new  User.Builder().userId((int)id).sex(u.getSex()).city(u.getCity()).province(u.getProvince()).country(u.getCountry()).avatarUrl(u.getAvatarUrl()).nickName(u.getNickName()).build();
	}

	public User update(User u) {
		currentSession().update(u);
		return new  User.Builder().userId(u.getUserId()).sex(u.getSex()).city(u.getCity()).province(u.getProvince()).country(u.getCountry()).avatarUrl(u.getAvatarUrl()).nickName(u.getNickName()).build();
	}

	public User findOneByOpenId(String openId) {
		List list = currentSession().createCriteria(User.class).add(Restrictions.eq("openId", openId)).list();
		if (list.size() > 0) {
			return (User) list.get(0);
		} else {
			return null;
		}
	}
}
